using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LTKJ.RTU
{
    /// <summary>
    /// 异步任务管理器 - 专业级异步操作管理
    /// </summary>
    public class AsyncTaskManager : IDisposable
    {
        private readonly ConcurrentDictionary<string, CancellationTokenSource> activeTasks;
        private readonly ConcurrentQueue<AsyncTaskInfo> taskQueue;
        private readonly SemaphoreSlim semaphore;
        private readonly System.Threading.Timer cleanupTimer;
        private readonly int maxConcurrentTasks = 10;
        private readonly int maxQueueSize = 1000;
        private volatile bool isDisposed = false;

        public event Action<string> OnTaskCompleted;
        public event Action<string> OnTaskError;
        public event Action<string> OnTaskTimeout;

        public AsyncTaskManager()
        {
            activeTasks = new ConcurrentDictionary<string, CancellationTokenSource>();
            taskQueue = new ConcurrentQueue<AsyncTaskInfo>();
            semaphore = new SemaphoreSlim(maxConcurrentTasks, maxConcurrentTasks);
            
            // 启动清理定时器
            cleanupTimer = new System.Threading.Timer(CleanupCompletedTasks, null, 30000, 30000); // 30秒清理一次
        }

        /// <summary>
        /// 执行异步任务
        /// </summary>
        public async Task<T> ExecuteTaskAsync<T>(Func<Task<T>> taskFunc, string taskName, int timeoutMs = 30000)
        {
            if (isDisposed) throw new ObjectDisposedException(nameof(AsyncTaskManager));

            var taskId = Guid.NewGuid().ToString();
            var cts = new CancellationTokenSource(timeoutMs);
            
            try
            {
                // 等待信号量
                await semaphore.WaitAsync(cts.Token);
                
                // 添加到活动任务列表
                activeTasks.TryAdd(taskId, cts);
                
                // 执行任务
                var result = await taskFunc();
                
                OnTaskCompleted?.Invoke($"任务 {taskName} 执行成功");
                return result;
            }
            catch (OperationCanceledException)
            {
                OnTaskTimeout?.Invoke($"任务 {taskName} 执行超时");
                throw;
            }
            catch (Exception ex)
            {
                OnTaskError?.Invoke($"任务 {taskName} 执行异常: {ex.Message}");
                throw;
            }
            finally
            {
                // 清理资源
                activeTasks.TryRemove(taskId, out _);
                cts?.Dispose();
                semaphore.Release();
            }
        }

        /// <summary>
        /// 执行无返回值的异步任务
        /// </summary>
        public async Task ExecuteTaskAsync(Func<Task> taskFunc, string taskName, int timeoutMs = 30000)
        {
            await ExecuteTaskAsync(async () =>
            {
                await taskFunc();
                return true;
            }, taskName, timeoutMs);
        }

        /// <summary>
        /// 执行同步任务（在线程池中）
        /// </summary>
        public async Task<T> ExecuteSyncTaskAsync<T>(Func<T> taskFunc, string taskName, int timeoutMs = 30000)
        {
            return await ExecuteTaskAsync(async () =>
            {
                return await Task.Run(taskFunc);
            }, taskName, timeoutMs);
        }

        /// <summary>
        /// 执行同步任务（无返回值）
        /// </summary>
        public async Task ExecuteSyncTaskAsync(Action taskAction, string taskName, int timeoutMs = 30000)
        {
            await ExecuteTaskAsync(async () =>
            {
                await Task.Run(taskAction);
            }, taskName, timeoutMs);
        }

        /// <summary>
        /// 排队执行任务
        /// </summary>
        public void QueueTask(Func<Task> taskFunc, string taskName, int priority = 0)
        {
            if (isDisposed) return;

            try
            {
                if (taskQueue.Count < maxQueueSize)
                {
                    var taskInfo = new AsyncTaskInfo
                    {
                        TaskFunc = taskFunc,
                        TaskName = taskName,
                        Priority = priority,
                        QueuedTime = DateTime.Now
                    };

                    taskQueue.Enqueue(taskInfo);
                    
                    // 启动队列处理器
                    _ = ProcessQueuedTasksAsync();
                }
                else
                {
                    OnTaskError?.Invoke($"任务队列已满，无法添加任务: {taskName}");
                }
            }
            catch (Exception ex)
            {
                OnTaskError?.Invoke($"添加任务到队列异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理队列中的任务
        /// </summary>
        private async Task ProcessQueuedTasksAsync()
        {
            while (!isDisposed && taskQueue.TryDequeue(out var taskInfo))
            {
                try
                {
                    await ExecuteTaskAsync(taskInfo.TaskFunc, taskInfo.TaskName);
                }
                catch (Exception ex)
                {
                    OnTaskError?.Invoke($"处理队列任务异常: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 清理已完成的任务
        /// </summary>
        private void CleanupCompletedTasks(object state)
        {
            if (isDisposed) return;

            try
            {
                var completedTasks = new List<string>();
                
                foreach (var kvp in activeTasks)
                {
                    if (kvp.Value.Token.IsCancellationRequested)
                    {
                        completedTasks.Add(kvp.Key);
                    }
                }

                foreach (var taskId in completedTasks)
                {
                    if (activeTasks.TryRemove(taskId, out var cts))
                    {
                        cts?.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                OnTaskError?.Invoke($"清理任务异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 取消所有活动任务
        /// </summary>
        public void CancelAllTasks()
        {
            try
            {
                foreach (var cts in activeTasks.Values)
                {
                    cts?.Cancel();
                }
            }
            catch (Exception ex)
            {
                OnTaskError?.Invoke($"取消任务异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取任务统计信息
        /// </summary>
        public TaskStatistics GetTaskStatistics()
        {
            return new TaskStatistics
            {
                ActiveTasks = activeTasks.Count,
                QueuedTasks = taskQueue.Count,
                AvailableSlots = semaphore.CurrentCount,
                MaxConcurrentTasks = maxConcurrentTasks
            };
        }

        /// <summary>
        /// 等待所有任务完成
        /// </summary>
        public async Task WaitForAllTasksAsync(int timeoutMs = 60000)
        {
            try
            {
                var timeoutCts = new CancellationTokenSource(timeoutMs);
                
                while (activeTasks.Count > 0 && !timeoutCts.Token.IsCancellationRequested)
                {
                    await Task.Delay(100, timeoutCts.Token);
                }
            }
            catch (OperationCanceledException)
            {
                OnTaskTimeout?.Invoke("等待任务完成超时");
            }
        }

        public void Dispose()
        {
            if (!isDisposed)
            {
                isDisposed = true;
                
                // 停止定时器
                cleanupTimer?.Change(Timeout.Infinite, Timeout.Infinite);
                
                // 取消所有任务
                CancelAllTasks();
                
                // 等待任务完成
                _ = WaitForAllTasksAsync(5000);
                
                // 清理资源
                cleanupTimer?.Dispose();
                semaphore?.Dispose();
                
                // 清空队列
                while (taskQueue.TryDequeue(out _)) { }
                
                // 清理活动任务
                foreach (var cts in activeTasks.Values)
                {
                    cts?.Dispose();
                }
                activeTasks.Clear();
            }
        }
    }

    /// <summary>
    /// 异步任务信息
    /// </summary>
    public class AsyncTaskInfo
    {
        public Func<Task> TaskFunc { get; set; }
        public string TaskName { get; set; }
        public int Priority { get; set; }
        public DateTime QueuedTime { get; set; }
    }

    /// <summary>
    /// 任务统计信息
    /// </summary>
    public class TaskStatistics
    {
        public int ActiveTasks { get; set; }
        public int QueuedTasks { get; set; }
        public int AvailableSlots { get; set; }
        public int MaxConcurrentTasks { get; set; }
    }
}
